from rest_framework import serializers
from django_redis import get_redis_connection

from oauth.models import OAuthQQUser
from oauth.utils import check_save_user_token
from users.models import User


class QQAuthUserSerializer(serializers.Serializer):
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')
    password = serializers.CharField(label='密码', max_length=20, min_length=8)
    sms_code = serializers.CharField(label='短信验证码', max_length=6, min_length=6)
    access_token = serializers.CharField(label='标识码')

    def validate(self, attrs):
        access_token = attrs['access_token']
        mobile = attrs['mobile']
        password = attrs['password']
        sms_code = attrs['sms_code']

        openid = check_save_user_token(access_token)
        if not openid:
            raise serializers.ValidationError('过期的token')
        attrs['openid'] = openid

        try:
            redis_conn = get_redis_connection('code')
            redis_sms_code = redis_conn.get('sms_'+mobile)
        except Exception as e:
            raise serializers.ValidationError('短信验证码过期')
        if redis_sms_code.decode() != sms_code:
            raise serializers.ValidationError('短信验证码写错')

        #判断用户有没有注册，没有注册就注册，有就绑定
        try:
            user = User.objects.get(mobile = mobile)
        except User.DoesNotExist:
            pass
        else:
            if not user.check_password(password):
                raise serializers.ValidationError('密码写错')
            #save()方法用到
            attrs['user'] =user
        return attrs


    #绑定
    def create(self, validated_data):
        user = validated_data.get('user')
        if not user:
            user = User.objects.create(username = validated_data.get('mobile'),
                                       mobile=validated_data.get('mobile'),
                                       password = validated_data.get('password')
                                       )
            user.set_password(validated_data.get('password'))
            user.save()

        openid = validated_data.get('openid')

        qquser = OAuthQQUser.objects.create(user = user,
                                   openid= openid
                                   )

        return qquser

